#include <stdio.h>
#include <time.h>
#include <assert.h>
#include <windows.h>

HWND ghMainWnd, ghOtherWnd;

LRESULT WINAPI OtherWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	switch (msg)
	{
		case WM_DESTROY:
			PostQuitMessage(0);
			break;

		default:
			return DefWindowProc(hWnd, msg, wParam, lParam);
	}
	return 0;
}

LRESULT WINAPI MainWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	switch (msg)
	{
		case WM_DESTROY:
			PostQuitMessage(0);
			break;

		default:
			return DefWindowProc(hWnd, msg, wParam, lParam);
	}
	return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	WNDCLASSEX wcex;
	MSG msg;

	// get a console.
	AllocConsole();
	freopen("CONOUT$", "w", stdout);
	freopen("CONOUT$", "w", stderr);
	freopen("CONIN$", "r", stdin);

	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wcex.hIconSm = wcex.hIcon;
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wcex.lpszMenuName = NULL;

	// create window with 'main' class.
	wcex.lpfnWndProc = MainWndProc;
	wcex.lpszClassName = "main";
	if (RegisterClassEx(&wcex) == 0) {
		MessageBox(NULL, "register main window class failure", NULL, MB_OK);
		return 0;
	}
	ghMainWnd = CreateWindowEx(0, wcex.lpszClassName, "Main Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 300, 200, NULL, NULL, hInstance, NULL);
	if (ghMainWnd == NULL) {
		MessageBox(NULL, "create main window failure", NULL, MB_OK);
		return 0;
	}
	ShowWindow(ghMainWnd, nCmdShow);
	UpdateWindow(ghMainWnd);


	// create window with 'other' class.
	wcex.lpfnWndProc = OtherWndProc;
	wcex.lpszClassName = "other";
	if (RegisterClassEx(&wcex) == 0) {
		MessageBox(NULL, "register other window class failure", NULL, MB_OK);
		return 0;
	}
	ghOtherWnd = CreateWindowEx(0, wcex.lpszClassName, "Other Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 300, 200, NULL, NULL, hInstance, NULL);
	if (ghOtherWnd == NULL) {
		MessageBox(NULL, "create other window failure", NULL, MB_OK);
		return 0;
	}
	ShowWindow(ghOtherWnd, nCmdShow);
	UpdateWindow(ghOtherWnd);

	// message loop.
	while (GetMessage(&msg, NULL, 0, 0) > 0) {
		printf("hwnd: %p\n", msg.hwnd);
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	putchar(getchar());
	MessageBox(0, 0, 0, 0);
	return 0;
}
